﻿using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Reflection;
using System.Xml;
using System.Xml.Serialization;
using Microsoft.TeamFoundation.VersionControl.Client;
using System.IO.IsolatedStorage;
using TeamReview.Services;
using System.Security.Principal;
using System.Diagnostics;
using System.Text.RegularExpressions;

namespace TeamReview.Settings
{
  /// <summary>
  /// Simple xml serialization class to persist form settings
  /// </summary>
  internal class SettingsReaderWriter
  {
    private TeamReviewSettings settings;
    private XmlSerializer serializer;
    private string configFile;


    public SettingsReaderWriter()
    {      
      serializer = new XmlSerializer(typeof(TeamReviewSettings));
      string version = FileVersionInfo.GetVersionInfo(Assembly.GetExecutingAssembly().Location).FileVersion;
      string username = Regex.Replace(WindowsIdentity.GetCurrent().Name, "\\W", "");
      string location = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
      configFile = string.Format("{0}\\TeamReview_{1}_{2}.config", location, version, username);
      settings = ReadSettings();
    }

    

    public void Add(WindowSetting window)
    {
      settings.WindowSettings.Add(window);
    }

    public WindowSetting Get(string windowName)
    {
        foreach(WindowSetting ws in settings.WindowSettings)
        {
            if(ws.Name.Equals(windowName, StringComparison.InvariantCultureIgnoreCase))
                return ws;
        }

        return null;
    }

    public void Add(TeamSetting teamSetting)
    {
      settings.TeamSettings.Add(teamSetting);
    }

    public TeamSetting Get(TeamProject project)
    {
        foreach(TeamSetting ts in settings.TeamSettings)
        {
            if(ts.ArtifactUri.Equals(project.ArtifactUri.ToString(), StringComparison.InvariantCultureIgnoreCase))
                return ts;
        }
        return null;
    }

    public void Save()
    {
      WriteSettings();
    }
    
    private TeamReviewSettings ReadSettings()
    {
      
      if (File.Exists(configFile))
      {
        using (XmlReader reader = XmlReader.Create(configFile))
        {
            return (TeamReviewSettings)serializer.Deserialize(reader);        
        }
      }

      //empty list
      return new TeamReviewSettings();
    }


    private void WriteSettings()
    {
      using (XmlWriter writer = XmlWriter.Create(configFile))
      {
        if (writer == null)
          throw new NullReferenceException();

        serializer.Serialize(writer, settings);
        
      }
    }

  }
}
